package com.thf.service.impl;

import com.alibaba.fastjson.JSON;
import com.thf.dao.AuthDao;
import com.thf.model.CommonResult;
import com.thf.model.Permission;
import com.thf.model.ResultData;
import com.thf.model.UserModel;
import com.thf.service.AuthService;
import com.thf.util.JwtTokenUtil;
import com.thf.util.ResultTool;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class AuthServiceImpl implements AuthService {

    @Resource
    private AuthDao authDao;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private JwtTokenUtil jwtTokenUtil;
    @Value("${jwt.tokenHead}")
    String tokenHead;
    @Override
    public ResultData login(UserModel userModel) {
        UserModel model = authDao.login(userModel.getUsername(),userModel.getPassword());
        if(model ==null){
            return new ResultData(ResultTool.CODE_ERROR, ResultTool.CODE_ERROR_MSG);
        }
        HashMap<String, String> data = new HashMap<>();
        Map<String,Object> map = new HashMap<>();
        map.put("username",model.getUsername());
        map.put("enable",model.getEnable());
        data.put("head",tokenHead);
        data.put("accessToken",jwtTokenUtil.generateToken(map));
        return new ResultData(ResultTool.CODE_SUCCES, ResultTool.CODE_SUCCES_MSG,data);
    }

    @Override
    public UserModel getUserByName(String name) {
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        if(redisTemplate.hasKey(name)){
            return JSON.parseObject(redisTemplate.boundValueOps(name).get().toString(),UserModel.class);
        }
        List<UserModel> users= authDao.getUserByName(name);
        Assert.isTrue(users.size()==1,"您输入的账户不存在，或者有多个相同的账户");
        String strJson = JSON.toJSONString(users.get(0));
        redisTemplate.boundValueOps(name).set(strJson,30, TimeUnit.MINUTES);
        return users.get(0);
    }

    @Override
    public List<Permission> getPermissionsByUserId(Integer id) {
        return authDao.getPermissionsByUserId(id);
    }

    @Override
    public Permission getPermissionsByUri(String uri) {
        return authDao.getPermissionsByUri(uri);
    }

    @Override
    public CommonResult checkAccessToUri(String uri, String username) {
        Permission permissionsByUri = getPermissionsByUri(uri);
        if(permissionsByUri == null){
            return  CommonResult.success(true);
        }
        UserModel userByName = getUserByName(username);
        List<Permission> permissionsByUserId = getPermissionsByUserId(userByName.getId());
        boolean b = permissionsByUserId.stream().anyMatch(wxPermission -> StringUtils.equals(wxPermission.getUri(), uri));
        CommonResult commonResult = b? CommonResult.success(true): CommonResult.forbidden(null);
        System.out.println(commonResult);
        return b? CommonResult.success(true): CommonResult.forbidden(null);
    }
}